package com.itheima.controller.backend.reservation;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.dto.OrderSettingDto;
import com.itheima.common.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @className OrderSettingController
 */
@RestController
@RequestMapping("/ordersetting")
@RequiredArgsConstructor
@Slf4j
public class OrderSettingController {

    private final OrderSettingService orderSettingService;

    /**
     * 下载模板文件
     * @param fileName 文件名
     * @return ResponseEntity<Resource>
     * @throws IOException
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadTemplate(@RequestParam("filename") String fileName) throws IOException {
        // 加载资源路径获取模板文件
        Resource resource = new ClassPathResource("templates/" + fileName);
        if (!resource.exists()) {
            throw new RuntimeException("模板文件不存在");
        }
        // 返回响应体：响应类型（二进制流数据）、响应头（附件下载模式）、响应体（资源模板文件）
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition",
                        "attachment; filename=\"" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + "\"")
                .body(resource);
    }

    /**
     * 修改预约人数
     * @param orderSettingDto 预约设置信息
     * @return Result
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSettingDto orderSettingDto) {
        orderSettingService.editNumberByOrderDate(orderSettingDto);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }

    /**
     * 根据月份查询预约设置信息
     * @param month 月份
     * @return Result
     */
    // @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam("month") String month){

        //TODO 返回集合数据，但前端未展示数据

        List<OrderSetting> orderSettings = orderSettingService.getOrderSettingByMonth(month);
        log.info("orderSettings集合:{}",orderSettings);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettings);
    }

    /**
     * 上传预约设置信息
     * @param excelFile excel文件
     * @return Result
     */
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile excelFile){
        orderSettingService.uploadFile(excelFile);
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }
}
